package org.weso.lodin.datasource.config;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.util.xml.DomUtils;
import org.w3c.dom.Document;
import org.weso.lodin.exceptions.DocumentBuilderException;
import org.weso.lodin.exceptions.LodinModelException;
import org.weso.lodin.generated.Dataset;
import org.weso.lodin.utils.DatasetXMLBind;
import org.weso.lodin.utils.DocumentBuilderHelper;


public class DatasetDirTemplateDAOImpl implements DatasetTemplateDAO {

	protected static Logger logger = Logger.getLogger(DatasetDirTemplateDAOImpl.class);
	private String dir;

	public DatasetDirTemplateDAOImpl(){
		this.dir = DatasetListing.defaultPathData;
		
	}
	public DatasetDirTemplateDAOImpl(String dir){
		this.dir = dir;
	}
	public List<Dataset> getDatasets() {
		File [] indicatorFiles = DatasetListing.listCustomIndicatorSources(this.dir);
		List<Dataset> indicatorTypes = new LinkedList<Dataset>();
		try {
			for(int i = 0; i<indicatorFiles.length;i++){
				logger.debug("Loading file: "+indicatorFiles[i]);
				InputStream in = new FileInputStream(indicatorFiles[i]);
				Document doc = DocumentBuilderHelper.getDocumentFromInputStream(in);
				Dataset value = DatasetXMLBind.getInstance().restoreIndicator(doc);
				logger.debug(value.getId()+" "+value.getIndicator());
				indicatorTypes.add(value);
			}	
		} catch (DocumentBuilderException e) {
			throw new LodinModelException(e, "Loading datasets types");
		} catch (FileNotFoundException e) {
			throw new LodinModelException(e, "Loading datasets file");
		}
		return indicatorTypes;
	}



}
